﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Luka.Log;

internal class StartupFilter : IStartupFilter
{
    // 实现IStartupFilter接口的Configure方法
    public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
    {
        // 返回一个Action<IApplicationBuilder>类型的委托
        return app =>
        {
            // 使用ReadBodyMiddleware中间件
            app.UseMiddleware<ReadBodyMiddleware>();
            // 初始化内部应用程序
            InitializeInternalApp(app);
            // 调用next(app)方法，执行下一个中间件
            next(app);
        };
    }

    // 提取初始化 InternalApp 属性的逻辑
    private void InitializeInternalApp(IApplicationBuilder app)
    {
        // 设置服务提供者
        InternalApp.Providers = app.ApplicationServices;

        // 设置配置对象，合并并构建配置
        InternalApp.Configuration = new ConfigurationBuilder().MergeConfiguration().Build();

        // 获取并设置宿主环境
        InternalApp.HostEnvironment = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();
    }
}